package com.itheima.tanhua.service;

import cn.hutool.core.collection.CollUtil;
import com.itheima.tanhua.api.RecommendApi;
import com.itheima.tanhua.api.UserInfoApi;
import com.itheima.tanhua.api.UserLikeApi;
import com.itheima.tanhua.api.VisitorsApi;
import com.itheima.tanhua.autoconfig.template.FaceTemplate;
import com.itheima.tanhua.autoconfig.template.OssTemplate;
import com.itheima.tanhua.domain.UserInfo;
import com.itheima.tanhua.exception.BusinessException;
import com.itheima.tanhua.mongo.RecommendUser;
import com.itheima.tanhua.mongo.UserLike;
import com.itheima.tanhua.mongo.Visitors;
import com.itheima.tanhua.utils.Constants;
import com.itheima.tanhua.utils.UserHolder;
import com.itheima.tanhua.vo.ErrorResult;
import com.itheima.tanhua.vo.PageResult;
import com.itheima.tanhua.vo.UserInfoVo;
import com.itheima.tanhua.vo.UserVo;
import org.apache.commons.lang.StringUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author Lff
 * @date 2022/3/24
 */
@Service
public class UserInfoService {
    @DubboReference
    private UserInfoApi userInfoApi;

    @Autowired
    private OssTemplate ossTemplate;

    @Autowired
    private FaceTemplate faceTemplate;

    @Autowired
    private RedisTemplate redisTemplate;

    @DubboReference
    private UserLikeApi userLikeApi;

    @DubboReference
    private VisitorsApi visitorsApi;

    @DubboReference
    private RecommendApi recommendApi;

    /**
     * 用户详情信息保存
     *
     * @param userInfo
     */
    public void save(UserInfo userInfo) {
        userInfoApi.save(userInfo);
    }

    /**
     * 修改用户信息
     *
     * @param id
     */
    public void updateHead(MultipartFile headPhoto, Long id) {

        //上传图片
        String url = null;
        try {
            url = ossTemplate.upload(headPhoto.getOriginalFilename(), headPhoto.getInputStream());
        } catch (IOException e) {
            e.printStackTrace();
        }
        //判断用户传入的头像是否包含人脸
        boolean hasFace = faceTemplate.hasFace(url);
        if (!hasFace) {
            //不包含人脸 删除图片
            ossTemplate.delete(url);
            throw new BusinessException(ErrorResult.faceError());
        }
        //封装UserInfo对象
        UserInfo userInfo = new UserInfo();
        userInfo.setId(id);
        userInfo.setAvatar(url);
        //修改
        userInfoApi.update(userInfo);
    }

    /**
     * 查询用户单个信息
     * 根据id
     *
     * @param userID
     * @return
     */
    public UserInfoVo findById(Long userID) {
        UserInfo userInfo = userInfoApi.findById(userID);
        UserInfoVo userInfoVo = new UserInfoVo();
        BeanUtils.copyProperties(userInfo, userInfoVo);
        String age = "";
        if (userInfo.getAge() != null) {
            age = userInfo.getAge().toString();
        }
        userInfoVo.setAge(age);

        return userInfoVo;
    }

    /**
     * 更新用户的信息
     *
     * @param userInfo
     */
    public void updateUserInfo(UserInfo userInfo) {
        userInfoApi.update(userInfo);
    }


    /**
     * 互相喜欢、喜欢、粉丝、谁看过我 - 翻页列表
     * <p>
     * type：
     * 1 互相关注
     * 2 我关注
     * 3 粉丝
     * 4 谁看过我
     * <p>
     * page	是    当前页数	1
     * <p>
     * pagesize	否	页尺寸    10
     * <p>
     * nickname	否	昵称
     */
    public PageResult findUserPage(Integer type, Integer page, Integer pagesize, String nickname) {
        //获取当前登录用户的id
        Long userId = UserHolder.getUser().getId();
        PageResult pr;
        List<UserVo> result = new ArrayList<>();
        //互相关注 我喜欢 粉丝
        if (type == 1 || type == 2 || type == 3) {
            //1 互相关注 2 我关注 3粉丝
            pr = userLikeApi.findUserLikePage(userId, type, page, pagesize);
            List<UserLike> likes = (List<UserLike>) pr.getItems();
            if (CollUtil.isEmpty(likes)) {
                return pr;
            }
            //抽取userId
            List<Long> ids = new ArrayList<>();
            // 我喜欢 互相关注 likeUserId
            if (type == 1 || type == 2) {
                ids = CollUtil.getFieldValues(likes, "likeUserId", Long.class);
                //根据id查询 并且传入条件nickname
                UserInfo condition = new UserInfo();
                condition.setNickname(nickname);
                //查询mysql填充用户基本信息
                Map<Long, UserInfo> userMap = userInfoApi.getUserInfosToMap(ids, condition);
                for (UserLike like : likes) {
                    //通过userLikeId获取userinfo
                    UserInfo userInfo = userMap.get(like.getLikeUserId());
                    if (userInfo != null) {
                        UserVo init = UserVo.initUserLike(userInfo, like);
                        result.add(init);
                    }
                }
                // 抽取 userId
            } else {
                ids = CollUtil.getFieldValues(likes, "userId", Long.class);
                //根据id查询 并且传入条件nicknamelikes = {ArrayList@12430}  size = 10
                UserInfo condition = new UserInfo();
                condition.setNickname(nickname);
                //查询mysql填充用户基本信息
                Map<Long, UserInfo> userMap = userInfoApi.getUserInfosToMap(ids, condition);
                for (UserLike like : likes) {
                    //通过userId获取userinfo
                    UserInfo userInfo = userMap.get(like.getUserId());
                    if (userInfo != null) {
                        UserVo init = UserVo.initUserLike(userInfo, like);
                        result.add(init);
                    }
                }
            }

            //查询陌生人列表
        } else if (type == 4) {
            //4谁看过我
            //获取Redis中的值
            String key = Constants.VISITORS;
            String hashKey = userId.toString();
            String dateStr = (String) redisTemplate.opsForHash().get(key, hashKey);
            Long date = StringUtils.isEmpty(dateStr) ? null : Long.valueOf(dateStr);

            pr = visitorsApi.findVisitorPage(userId, date, page, pagesize);
            //更新redis中的时间数据
            redisTemplate.opsForHash().put(key, hashKey, System.currentTimeMillis() + "");
            List<Visitors> visitors = (List<Visitors>) pr.getItems();
            if (CollUtil.isEmpty(visitors)) {
                return pr;
            }
            //抽取id
            List<Long> ids = CollUtil.getFieldValues(visitors, "visitorUserId", Long.class);
            //查询mysql-userInfo
            UserInfo condition = new UserInfo();
            condition.setNickname(nickname);
            Map<Long, UserInfo> userMap = userInfoApi.getUserInfosToMap(ids, condition);
            for (Visitors visitor : visitors) {
                UserInfo userInfo = userMap.get(visitor.getVisitorUserId());
                if (userInfo != null) {
                    UserVo userVo = UserVo.initVisitors(userInfo, visitor);
                    result.add(userVo);
                }
            }
        } else {
            throw new BusinessException(ErrorResult.error());
        }
        pr.setItems(result);
        return pr;
    }
}
